//
//  ReportOpenDef.m
//  LookyLoo
//
//  Created by Hilary Muludiang on 12/22/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ReportOpenDefViewController.h"
#import "RMCloudMadeMapSource.h"
#import "RMMarkerManager.h"
#import "SBJson.h"

@implementation ReportOpenDefViewController

@synthesize reportDate;
@synthesize reportTime;
@synthesize submitReportBtn;
@synthesize locManager;
@synthesize locationLabel;
@synthesize babyButton;
@synthesize womanButton;
@synthesize manButton;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelSubmit:)] autorelease];
	
	NSDate *todaysDate = [[NSDate alloc] init];
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"MMMM d, yyyy"];
	[reportDate setText:[dateFormat stringFromDate:todaysDate]];
	[dateFormat	setDateFormat:@"hh:mm:ssa"];
	reportTime.text = [dateFormat stringFromDate:todaysDate];
	[dateFormat release];
	[todaysDate release];
	
	// Get location
	locManager = [[CLLocationManager alloc] init];
	locManager.delegate = self;
	locManager.desiredAccuracy = kCLLocationAccuracyBest;
	locManager.distanceFilter = 50; // meters traveled before another update is done
	[locManager startUpdatingLocation];
	
}

-(void) addMarkerAt:(CLLocationCoordinate2D) markerPosition
{
    UIImage *blueMarkerImage = [UIImage imageNamed:@"marker-blue.png"];
    RMMarker *newMarker = [[RMMarker alloc] initWithUIImage:blueMarkerImage anchorPoint:CGPointMake(0.5, 1.0)];
    [testMap.contents.markerManager addMarker:newMarker AtLatLong:markerPosition];
    [newMarker release];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
	if (error.code == kCLErrorDenied){
		//Turn off location manager updates
		[manager stopUpdatingLocation];
		[locManager release];
		locManager = nil;
	}
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *) newLocation fromLocation:(CLLocation *)oldLocation{
	NSString *coordDesc = @"Not Available";
	NSString *altDesc = @"Not Available";
	
	if (newLocation.horizontalAccuracy >= 0){
		coordDesc = [NSString stringWithFormat:@"%f, %f +/- %f meters",
					 newLocation.coordinate.latitude,
					 newLocation.coordinate.longitude,
					 newLocation.horizontalAccuracy];
	}
	if (newLocation.verticalAccuracy >=0) {
		altDesc = [NSString stringWithFormat:@"%f +/- %f meters",
				   newLocation.altitude, newLocation.verticalAccuracy];
	}
	NSLog(@"Latitude/Longitude: %@  \nAltitude: %@",
		  coordDesc, altDesc);
	
	id cmTilesource = [[[RMCloudMadeMapSource alloc] initWithAccessKey: @"13dc0c7930eb4a248f5ca4b3a96aed8c" 
                                                           styleNumber: 1] autorelease];
	
    [[[RMMapContents alloc] initWithView:testMap tilesource: cmTilesource] autorelease];
	
    CLLocationCoordinate2D initLocation;
	
    initLocation.longitude = newLocation.coordinate.longitude; // -0.127523;
    initLocation.latitude  = newLocation.coordinate.latitude; // 51.51383;
	
    [testMap moveToLatLong: initLocation];
	
    [testMap.contents setZoom: 16];
	[self addMarkerAt:initLocation];
	
	// Get reverse geocode info
	[self getLocationDetails:[NSString stringWithFormat:@"%f", initLocation.latitude] andLongitude:[NSString stringWithFormat:@"%f",initLocation.longitude]];
}

-(void)getLocationDetails:(NSString *) latitude andLongitude:(NSString *) longitude{
	// http:// nominatim.openstreetmap.org/reverse?format=json&lat=<lat>&lon=<long>&zoom=18&addressdetails=1
	NSString *geocodeURL = [NSString stringWithFormat:@"http://nominatim.openstreetmap.org/reverse?format=json&lat=%@&lon=%@&zoom=18&addressdetails=1", latitude, longitude];
	NSLog(@"Geocode URL: %@", geocodeURL);
	
	// Create NSURL string from formatted string
	NSURL *url = [NSURL URLWithString:geocodeURL];
	NSLog(@"url : %@", url);
	// Setup and start async download
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	[connection release];
	[request release];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	// Store incoming data into a string
	NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	NSLog(@"jsonString: %@", jsonString);
	
	// Create a dictionary from the JSON string
	NSDictionary *results = [jsonString JSONValue];
	
	// Build an array from the dictionary for easy access to each entry
	NSArray *geocacheResponse = [results objectForKey:@"address"];
	NSLog(@"geonames array: %@", geocacheResponse);
	
	
	/*for (NSDictionary *country in geonames)
	{
		// Get title of the image
		NSString *capital = [country objectForKey:@"capital"];
		
		// Save the title to the photo titles array
		[capitalCities addObject:(capital.length > 0 ? capital : @"Untitled")];
		
		// Build the URL to where the image is stored (see the Flickr API)
		// In the format http://farmX.static.flickr.com/server/id_secret.jpg
		// Notice the "_s" which requests a "small" image 75 x 75 pixels
	    NSLog(@"Capital city: %@", capital);
		
	}*/
}


-(IBAction)cancelSubmit:(UIBarButtonItem *)sender{
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)submitOpenDefReport:(UIButton *)sender{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Report Submitted" message:@"Thank you for helping your community by submitting this report." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {	
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)selectedPersonButton:(UIButton *)sender{
	if (sender.tag == 1) {
		[sender setSelected:YES];
		[womanButton setSelected:NO];
		[manButton setSelected:NO];
	}else if (sender.tag ==2 ) {
		[sender setSelected:YES];
		[babyButton setSelected:NO];
		[manButton setSelected:NO];
		
	} else if (sender.tag == 3 ){
		[sender setSelected:YES];
		[womanButton setSelected:NO];
		[babyButton setSelected:NO];
	}

}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[reportTime release];
	[reportDate release];
	[submitReportBtn release];
	[locManager release];
	[locationLabel release];
	[babyButton release];
	[womanButton release];
	[manButton release];
    [super dealloc];
}


@end
